package com.web;

import com.annotation.ComponentScan;
import com.annotation.Controller;
import com.annotation.RequestMapping;
import com.config.SpringMVCConfig;
import com.method.HandlerMethod;
import com.utils.ReflexUtils;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author 龙小虬
 * @date 2021/3/15 11:30
 */
public class RequestMappingHandlerMapping {

    private final Map<String, HandlerMethod> registryMapping = new HashMap<String, HandlerMethod>();

    // 初始化mvc容器
    public void registryMapping(){
        // 1.获取@ComponentScan注解的类名
        ComponentScan declaredAnnotation = SpringMVCConfig.class.getDeclaredAnnotation(ComponentScan.class);
        // 若没有就跳出
        if(declaredAnnotation == null){
            return;
        }
        String springmvcPackage = declaredAnnotation.value();
        // 有注解但没有value跳出
        if(StringUtils.isEmpty(springmvcPackage)){
            return;
        }
        // 2.使用java反射机制获取类上加有@Controller注解的类
        Set<Class<?>> classes = ReflexUtils.getClasses(springmvcPackage);
        // 3.遍历每一个类 查找类上是否加有RequestMapping注解
        for (Class<?> c: classes) {
            // 查找类上的注解
            Controller controller = c.getDeclaredAnnotation(Controller.class);
            // 若没有就查看下一个类
            if(controller == null){
                continue;
            }
            // 获取含有@Controller的类的所有方法
            Method[] declaredMethods = c.getDeclaredMethods();
            for (Method m : declaredMethods) {
                RequestMapping requestMapping = m.getDeclaredAnnotation(RequestMapping.class);
                // 若方法上含有@RequestMapping就获取其value
                if(requestMapping != null){
                    String url = requestMapping.value();
                    // 获取value并且将value和对象 put到registryMapping 对象必须实例化
                    registryMapping.put(url,new HandlerMethod(m,newInstance(c)));
                }
            }
        }
    }

    /**
     * 在registryMapping中通过url查找相应的对象和方法
     * @param url
     * @return
     */
    public HandlerMethod getHandler(String url) {
        return registryMapping.get(url);
    }

    private Object newInstance(Class classInfo) {
        try {
            Object value = classInfo.newInstance();
            return value;
        } catch (Exception e) {
            return null;
        }
    }



}
